package com.aijk.commons.jedis;

import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
import redis.clients.jedis.JedisCluster;

/**
 * Redis 集群注解缓存实现
 * Created by ChenDeWei on 2016/6/7.
 */
public class JedisClusterCache implements Cache {
    private JedisCache redisCache;
    private String name;

    public JedisClusterCache(String name, int expire, JedisCluster jedisCluster) {
        this.name = name;
        this.redisCache = new JedisCache(name, expire, jedisCluster);
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public Object getNativeCache() {
        return this.redisCache;
    }

    @Override
    public ValueWrapper get(Object key) {
        final String keyf = (String) key;
        Object object = redisCache.get(keyf);
        return (object != null ? new SimpleValueWrapper(object) : null);
    }

    @Override
    public <T> T get(Object key, Class<T> type) {
        ValueWrapper wrapper = get(key);
        return wrapper == null ? null : (T) wrapper.get();
    }

    @Override
    public void put(Object key, Object value) {
        redisCache.put(key, value);
    }

    @Override
    public ValueWrapper putIfAbsent(Object key, Object value) {
        ValueWrapper wrapper = null;
        value = redisCache.get(key.toString());
        if (value != null) {
            wrapper = new SimpleValueWrapper(value);
        }
        return wrapper;
    }

    @Override
    public void evict(Object key) {
        redisCache.delete(key.toString());
    }

    @Override
    public void clear() {
        redisCache.clear();
    }

    public void setName(String name) {
        this.name = name;
    }
}
